/*
-------------------------------------------------------------------
BIE is Copyright 2001-2003 Brunswick Corp.
-------------------------------------------------------------------
Please read the legal notices (docs/legal.txt) and the license
(docs/bie_license.txt) that came with this distribution before using
this software.
-------------------------------------------------------------------
*/
package com.webdeninteractive.sbie.v1_1.util.xmlsvelte;

import java.util.Iterator;
import org.w3c.dom.Document;
// import org.w3c.dom.Element; // not imported: name conflict
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

public class DOMBuilder {

    public static org.w3c.dom.Document buildDOMDocument( Element sroot )
        throws ParserConfigurationException
    {
        Document doc = DocumentBuilderFactory.newInstance().
            newDocumentBuilder().newDocument();
        org.w3c.dom.Element root = doc.createElement( sroot.name );
        buildElement( doc, root, sroot );
        doc.appendChild( root );
        return doc;

    } // buildDOMDocument()

    // Recursive method which sets attributes and text on the
    // current element being built, and then does the same for its
    // child elements.
    public static void buildElement( org.w3c.dom.Document owner,
                              org.w3c.dom.Element current,
                              Element scurr )
    {
        Iterator attrnames = scurr.attrs.keySet().iterator();
        // add all attributes from scurr -> current
        while( attrnames.hasNext() ) {
            String name = (String)attrnames.next();
            String value = (String)scurr.attrs.get(name);
            current.setAttribute(name, value);
        }
        // add text node scurr->current if needed
        if ( scurr.text != null ) {
            current.appendChild(
                owner.createTextNode( scurr.text ) );
        }
        // create and append child elements
        Iterator children = scurr.kids.iterator();
        while( children.hasNext() ) {
            Element skid = (Element)children.next();
            org.w3c.dom.Element ekid = owner.createElement( skid.name );
            buildElement( owner, ekid, skid );
            current.appendChild( ekid );
        }

    } // buildElement()

}
